//
//  Dc_PlayerViewController.m
//  艾薇贝儿
//
//  Created by dllo on 15/9/9.
//  Copyright (c) 2015年 dllo－－邴鹏超. All rights reserved.
//

#import "Dc_PlayerViewController.h"
#import "STKAudioPlayer.h"
#import "Dc_Dan.h"
#import "MBProgressHUD.h"
#import "Dc_PlayerSTK.h"
#import "UIImageView+WebCache.h"
#import "DataBase.h"
#import "AppDelegate.h"

@interface Dc_PlayerViewController ()<STKAudioPlayerDelegate>
{UILabel *_tishi;
    Dc_PlayerSTK *player;
    NSInteger _count;
    
}

@property(nonatomic,retain)UIButton *preButton;
@property(nonatomic,retain)UIImageView *backImageView;
@property(nonatomic,retain)UILabel *songNameLabel;
@property(nonatomic,copy)NSString *songName;
@property(nonatomic,copy)NSString *singerName;
@property(nonatomic,copy)NSString *detail;
@property(nonatomic,assign)NSInteger songLenth;
@property(nonatomic,retain)UILabel *songDetail;
@property(nonatomic,copy)NSString *duration;
@property(nonatomic,retain)UIImageView *backImage;
@property(nonatomic,retain) UIImageView * PlayBackImageView;
@property(nonatomic,retain)MBProgressHUD *HUD;
@end
@implementation Dc_PlayerViewController
-(void)viewWillAppear:(BOOL)animated
{
    
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"STATE"] isEqualToString:@"YES"]) {
        _playButton.selected= YES;
    }
    else if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"STATE"] isEqualToString:@"NO"])
    {
        _playButton.selected= NO;

    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[DataBase shareDataBase ] openDB];
    
    [[DataBase shareDataBase] createTable];
    
    //初始化播放器
    player = [Dc_PlayerSTK shareHandleController];
    player.delegate=self;
   
    NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(cene) name:@"MaxTime" object:nil];
    
    
    self.playerIndex = [Dc_Dan shareDan].index;
    
    //背景图片
    self.backImageView=[[UIImageView alloc]initWithFrame:self.view.frame];
    self.backImageView.image=[UIImage imageNamed:@"hai.jpg"];
    [self.view addSubview:self.backImageView];
    
    //毛玻璃效果
    UIVisualEffectView * visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
    visualEfView.frame = self.view.frame;
    visualEfView.backgroundColor=[UIColor cyanColor];
    visualEfView.alpha = 0.2;
    [self.backImageView  addSubview:visualEfView];
    
    
    self.PlayBackImageView = [[ UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-32, self.view.frame.size.height-64-10, 64, 64)];
    
    
    [self.view addSubview:self.PlayBackImageView];
    self.PlayBackImageView.layer.masksToBounds = YES;
    self.PlayBackImageView.layer.cornerRadius = 35 ;
    [self setview];
    
}
-(void)cene{
    
    [self nextButtonEvent];
    
}
-(void)setview{
    self.backImage=[[UIImageView alloc]init ];
    [self.backImage.layer setMasksToBounds:YES];
    //传网络图片
    NSURL *ur = [Dc_Dan shareDan].image;
    //歌手图片
    [self.backImage sd_setImageWithURL:ur placeholderImage:[UIImage imageNamed:@"66.jpg"]];
    [self.backImage setFrame:CGRectMake(0,110*OffHeight , 375*OffWidth, 300*OffHeight)];
    [self.backImage setAlpha:0.8];
    [self.view addSubview:self.backImage];
    
    
    //收藏按钮
    self.like=[UIButton buttonWithType:UIButtonTypeCustom];
    self.like.frame=CGRectMake(self.view.frame.size.width-60, 20, 40, 40);
    [self.like setImage:[UIImage imageNamed:@"shi.png"] forState:UIControlStateNormal];
    [self.like addTarget:self action:@selector(like:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.like];
    

    
    //返回按钮
    UIButton *back=[UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(0, 20, 40, 40);
    
    [back setImage:[UIImage imageNamed:@"fanhui"]forState:UIControlStateNormal];
    [self.view addSubview:back];
    
    //返回按钮手势
    UITapGestureRecognizer * back1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
    [back addGestureRecognizer:back1];
    
    //歌曲名字
    _singname=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    [_singname setCenter:CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/1.5)];
    [_singname setFont:[UIFont fontWithName:@"AmericanTypewriter-Bold" size:25.0]];
    //负值
    _singname.text=[Dc_Dan shareDan].singname;
    _singname.textColor=[UIColor cyanColor];
    _singname.textAlignment=1;
    [self.view addSubview:_singname];
    
    
    //歌手名字
    _singername=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    [_singername setCenter:CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/1.3)];
    [_singername setFont:[UIFont fontWithName:@"Georgia" size:15.0]];
    _singername.textColor=[UIColor cyanColor];
    _singername.text= [Dc_Dan shareDan].singername;
    _singername.textAlignment=1;
    [self.view addSubview:_singername];
    
    
    
    //给歌手图片一个效果
//    CABasicAnimation *monkeyAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
//    monkeyAnimation.toValue = [NSNumber numberWithFloat:2.0 *M_PI];
//    monkeyAnimation.duration = 1.5;
//    monkeyAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
//    monkeyAnimation.cumulative = NO;
//    monkeyAnimation.removedOnCompletion = NO; //No Remove
//    monkeyAnimation.repeatCount = FLT_MAX;
//    [self.backImage.layer addAnimation:monkeyAnimation forKey:@"AnimatedKey"];
//    self.backImage.layer.speed = 0.2;
//    self.backImage.layer.beginTime = 0.0;
//    
    
    //音量按钮
    
    
    
    _yinbutton=[UIButton buttonWithType:UIButtonTypeCustom];
    _yinbutton.frame=CGRectMake(self.view.frame.size.width-60, self.view.frame.size.height-63, 40, 40);
    [_yinbutton setImage:[UIImage imageNamed:@"shengyin.png"] forState:UIControlStateNormal];
    [_yinbutton addTarget:self action:@selector(hidden:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_yinbutton];
    
    
    //开始时间
    _currentPlaybackTime = [[UILabel alloc] initWithFrame:CGRectMake(5,self.view.frame.size.height-64-10 - 25 , 50, 25)];
    _currentPlaybackTime.font =[UIFont boldSystemFontOfSize:14.0f];
    _currentPlaybackTime.textAlignment = NSTextAlignmentCenter;
    _currentPlaybackTime.textColor = [UIColor blackColor];
    _currentPlaybackTime.text = @"00:00";
    [self.view addSubview:_currentPlaybackTime];
    
    
    //总长时间
    _totalPlaybackTime = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width-53, self.view.frame.size.height-64-10 - 25 , 50, 25)];
    _totalPlaybackTime.font =[UIFont boldSystemFontOfSize:14.0f];
    _totalPlaybackTime.textAlignment = NSTextAlignmentCenter;
    _totalPlaybackTime.textColor = [UIColor blackColor];
    _totalPlaybackTime.text = @"00:00";
    [self.view addSubview:_totalPlaybackTime];
    
    
    //进度条
    progress = [[UISlider alloc]initWithFrame:CGRectMake(0,self.view.frame.size.height-99, self.view.frame.size.width , 5)];
    progress.continuous = YES;
    progress.backgroundColor=[UIColor blueColor];
    progress.minimumTrackTintColor = [UIColor cyanColor];
    progress.maximumTrackTintColor = [UIColor whiteColor];
    [progress addTarget:self action:@selector(PlaySlider:) forControlEvents:UIControlEventValueChanged];
    //progress.Value = player.progress;
    [progress setThumbImage:[UIImage imageNamed:@"yuan.png"] forState:UIControlStateNormal];
    [self.view addSubview:progress];
    _tishi=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-30, self.view.frame.size.height-64-10 - 20-20-12, self.view.frame.size.width/3, 40)];
    _tishi.textColor=[UIColor whiteColor];
    [self.view addSubview:_tishi];
    
    
    //声音控件
    _volumeSlider= [[UISlider alloc] initWithFrame:CGRectMake(self.view.frame.size.width-110, self.view.frame.size.height-170, 130, 5)];
    _volumeSlider.maximumValue=20;
    _volumeSlider.minimumValue=0;
    _volumeSlider.minimumTrackTintColor = [UIColor cyanColor];
    _volumeSlider.maximumTrackTintColor = [UIColor lightGrayColor];
    [_volumeSlider setThumbImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
    _volumeSlider.value=4;
    _volumeSlider.hidden=YES;
    [_volumeSlider addTarget:self action:@selector(volumeSet:) forControlEvents:UIControlEventValueChanged];
    _volumeSlider.transform= CGAffineTransformMakeRotation(-90* M_PI/180);
    [self.view addSubview:_volumeSlider];
    
    
    //播放键
    
    _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake(self.view.frame.size.width/2-64/2, self.view.frame.size.height-64-10, 64, 64);
    [_playButton setImage:[UIImage imageNamed:@"pu.png"] forState:UIControlStateNormal];
    [_playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateSelected];
    [_playButton addTarget:self action:@selector(playButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playButton];
    
    
    //上一首
    
    self.preButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.preButton.frame = CGRectMake(_playButton.frame.origin.x-60, _playButton.frame.origin.y+8, 48, 48);
    [self.preButton setImage:[UIImage imageNamed:@"preSong.png"] forState:UIControlStateNormal];
    [self.preButton addTarget:self action:@selector(preButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.preButton];
    [_preButton release];
    
    //下一首
    
    _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextButton.frame = CGRectMake(_playButton.frame.origin.x+70, _playButton.frame.origin.y+8, 48, 48);
    [_nextButton setImage:[UIImage imageNamed:@"nextSong.png"] forState:UIControlStateNormal];
    [_nextButton addTarget:self action:@selector(nextButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextButton];
    
    //播放模式
    
    _playbackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playbackButton.frame =  CGRectMake(5, _preButton.frame.origin.y, 48, 48);
    [_playbackButton setImage:[UIImage imageNamed:@"xunhuan.png"] forState:UIControlStateNormal];
    [_playbackButton addTarget:self action:@selector(playBackButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playbackButton];
    
    
    //定时器
    self.mytime=[NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
    
}
-(void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}
//点击收藏
-(void)like:(UIButton *)button{
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.mode = MBProgressHUDModeText;

    [HUD show:YES];
    [HUD hide:YES afterDelay:1];
    [self.view addSubview:HUD];
    
    
    
    if ([[Dc_Dan shareDan].urlarray objectAtIndex:self.playerIndex]!=nil) {
        DcFirstModel *mod = [[Dc_Dan    shareDan].urlarray objectAtIndex:self.playerIndex];
        
        mod.url = [Dc_Dan shareDan].url;
        
        _count = 0;
        
        for (DcFirstModel * dcmodel in [[DataBase shareDataBase] selectModel]) {
            
            if ([dcmodel.name isEqualToString:mod.name]) {
                _count++;
            }
        }
        if (_count==0) {
            
            [[DataBase shareDataBase] insertModelInfo:mod];
            
            HUD.labelText = @"收藏成功";
        }
        else
        {
           HUD.labelText = @"取消收藏";
            for (DcFirstModel * m  in [[DataBase shareDataBase] selectModel]) {
                if ([m.name isEqualToString:mod.name]) {
                    [[DataBase shareDataBase] deleteModelInfo:m.number];
                }
            }
        }
        
    }
    else
    {
        
        HUD.labelText = @"当前没有歌曲";
    }
    
//    if(button.selected==YES){
//        button.selected=NO;
//          [self.like setImage:[UIImage imageNamed:@"shi"] forState:UIControlStateNormal];
//        
//    }else {
//        
//        button.selected=YES;
//            [self.like setImage:[UIImage imageNamed:@"kon"] forState:UIControlStateNormal];
//    }
//   
    
    
    
}



//选取歌曲音质
- (void)playMusic:(NSInteger)playIndex
{
    DcFirstModel *lisModel = [[Dc_Dan shareDan].urlarray objectAtIndex:playIndex];
    [self nameGet:lisModel];
    if (lisModel.url) {
        [player play:lisModel.url];
    }else
    {
        if(lisModel.auditionList.count >2) {
            NSDictionary *dic = [lisModel.auditionList objectAtIndex:1];
            NSString *url = [dic objectForKey:@"url"];
            [player play:url];
        }if (lisModel.auditionList.count==1) {
            NSDictionary *dic = [lisModel.auditionList objectAtIndex:0];
            NSString *url = [dic objectForKey:@"url"];
            [player play:url];
        }
    }
}
-(void)nextButtonEvent
{
    if ([Dc_Dan shareDan].way == PlayWithWaySole) {//如果为顺序循环播放
        if (self.playerIndex == [[Dc_Dan shareDan].urlarray count]-1) {
            self.playerIndex  = 0;
            [self playMusic:self.playerIndex ];
            return;
        }
        [self playMusic:++self.playerIndex ];
    }
    if (([Dc_Dan shareDan].way  == PlayWithWayRandom)){// 如果是随机
        self.playerIndex  = arc4random() % [Dc_Dan shareDan].urlarray.count;
        [self playMusic:self.playerIndex ];
    }
    if (([Dc_Dan shareDan].way  == PlayWithWayOneSongCirculation))
    { // 如果是单曲
        [self playMusic:self.playerIndex ];
    }
    //上一首
}-(void)preButtonEvent{
    if ([[Dc_Dan shareDan].urlarray count]!=0) {
        self.playerIndex-=1;
        if (self.playerIndex<0) {
            self.playerIndex = 0;
            HUD.labelText = @"第一首歌曲";
        }
        [self playMusic:self.playerIndex];
    }
}


//歌名和歌手名字方法
- (void)nameGet:(DcFirstModel *)model
{
    _singname.text= model.name;
    _singername.text = model.singerName;
    [Dc_Dan shareDan].singname = model.name;
    [Dc_Dan shareDan].singername = model.singerName;
}


-(void)PlaySlider:(id)sender{
    if (player) {
        UISlider * processSlider = sender;
        [player seekToTime:processSlider.value];
        
    }
    
}
//音量隐藏
-(void)hidden:(UIButton *)btn
{ if (btn.selected == NO)
{
    btn.selected = YES;
    [_volumeSlider setHidden:NO];
    
}
else
{
    [_volumeSlider setHidden:YES];
    btn.selected = NO;
}
    
    
}
//音量设置
-(void)volumeSet:(UISlider*)slider
{
    [player setVolume:slider.value];   
}
//显示时间
- (void)track
{
    if (progress) {
        progress.maximumValue = player.duration;
        progress.value = player.progress;
        NSInteger proMin = (NSInteger)player.progress / 60;
        NSInteger proSec = (NSInteger)player.progress % 60;
        NSInteger durMin = (NSInteger)player.duration / 60;
        NSInteger durSec = (NSInteger)player.duration % 60;
        
        _currentPlaybackTime.text = [NSString stringWithFormat:@"%02ld:%02ld", (long)proMin, (long)proSec];
        _totalPlaybackTime.text=[NSString stringWithFormat:@"%02ld:%02ld" , (long)durMin, (long)durSec];
        _tishi.text = player.state == STKAudioPlayerStateBuffering ? @"缓冲中..." : @"";
        
    }
}

//播放按钮暂停 动画取消
-(void)playButton:(UIButton *)btn
{
    if (btn.selected ==NO)
    {
        btn.selected = YES;
        [player pause];
        [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"STATE"];
        CFTimeInterval pausedTime = [self.backImage.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        self.backImage.layer.speed = 0.0;
        self.backImage.layer.timeOffset = pausedTime;
    }
    else
        
    {
        [player resume];
        [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"STATE"];
        CFTimeInterval pausedTime = [self.backImage.layer timeOffset];
        self.backImage.layer.speed = 0.2;
        self.backImage.layer.timeOffset = 0.0;
        self.backImage.layer.beginTime = 0.0;
        CFTimeInterval timeSincePause = [self.backImage.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
        self.backImage.layer.beginTime = timeSincePause;
        btn.selected = NO;
    }
}


//播放模式
-(void)playBackButtonEvent
{
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.mode = MBProgressHUDModeText;
    [HUD show:YES];
    [HUD hide:YES afterDelay:1];
    [self.view addSubview:HUD];
    if ([Dc_Dan shareDan].way == PlayWithWayOneSongCirculation) {//单曲循环播放
        [_playbackButton setImage:[UIImage imageNamed: @"suijibofang.png"] forState:UIControlStateNormal];
        [Dc_Dan shareDan].way = PlayWithWayRandom;
        HUD.labelText = @"随机";
        [Dc_Dan shareDan].way = PlayWithWayRandom;
        return;
    }
    if ([Dc_Dan shareDan].way == PlayWithWayRandom){//随机播放
        [_playbackButton setImage:[UIImage imageNamed:@"shunxu.png"] forState:UIControlStateNormal];
        [Dc_Dan shareDan].way = PlayWithWaySole;
        HUD.labelText = @"顺序";
        return;
    }
    else{//顺序循环
        [_playbackButton setImage:[UIImage imageNamed:@"danqu.png"] forState:UIControlStateNormal];
        [Dc_Dan shareDan].way = PlayWithWayOneSongCirculation;
        HUD.labelText = @"单曲";
        return;
    }
}


//  代理方法
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"开始播放");
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"完成加载");
}
/// Raised when the state of the player has changed
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    
}
/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    if (audioPlayer.state==STKAudioPlayerStateStopped) {
        
        
        NSNotificationCenter *playAnimation = [NSNotificationCenter defaultCenter];
        [playAnimation postNotificationName:@"MaxTime" object:nil];
        
    }
    
    
}
/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"错误原因: %d", errorCode);
}


/// Optionally implemented to get logging information from the STKAudioPlayer (used internally for debugging)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer logInfo:(NSString*)line
{
    NSLog(@"信息: %@", line);
}
/// Raised when items queued items are cleared (usually because of a call to play, setDataSource or stop)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didCancelQueuedItems:(NSArray*)queuedItems
{
    NSLog(@"未知");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
